package com.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.entity.Dep;
import com.service.DepServiceImpl;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@RequestMapping({"/api"})
public class DepController {

    @Autowired
    private DepServiceImpl depService;

    @Autowired
    private HttpServletRequest request;

    @Value("${upload.dir}")
    private String tmp;

    @GetMapping({"/searchDep"})
    public ResponseBean searchDep(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int limit,Integer depId,String depName){
        IPage result = depService.searchDep(page, limit, depId, depName);
        System.out.println("name:"+depName);
        return new ResponseBean(0,result.getTotal(),result.getRecords());
    }

    @PostMapping({"/addDep"})
    public ResponseBean addDep(Dep dep){
        boolean f=depService.save(dep);

        int code=f?200:500;
        if (code==200){
            String descDir=request.getServletContext().getRealPath("/images");
            System.out.println("descDir===:"+descDir);

            File descDirFile=new File(descDir);
            System.out.println("descDirFile===:"+descDirFile);
            if (descDirFile.exists()==false){
                descDirFile.mkdirs();
                System.out.println("mkdirs=====");
            }
            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);

        }
        return new ResponseBean(code,0,null);
    }


    @PutMapping({"/updateDep"})
    public ResponseBean updateDep(Dep dep){
        boolean f=depService.updateById(dep);
        int code=f?200:500;
        if (code==200) {
            String descDir = request.getServletContext().getRealPath("/images");
            File descDirFile = new File(descDir);
            if (descDirFile.exists() == false) {
                descDirFile.mkdirs();
            }
            FileUtil.copy(tmp + "/" + dep.getImage(), descDir + "/" + dep.getImage(), true);

        }
        return new ResponseBean(code,0,null);
    }


    @DeleteMapping({"/removeDepById/{depid}"})
    public ResponseBean removeDepById(@PathVariable String depid){
        boolean f=depService.removeById(depid);
        int code=f?200:500;
        System.out.println(code);
        return new ResponseBean(code,0,null);
    }


}
